package com.iakuil.mvp.mp.config;

import com.iakuil.mvp.mp.security.CustomSessionManager;
import com.iakuil.mvp.mp.security.CustomShiroFilter;
import com.iakuil.mvp.mp.security.WxCodeRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * Shiro配置
 *
 * @author Kai
 */
@Configuration
public class ShiroConfig {

    @Bean
    WxCodeRealm wxCodeRealm() {
        return new WxCodeRealm();
    }

    @Bean
    DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setSessionManager(new CustomSessionManager());
        manager.setRealm(wxCodeRealm());
        return manager;
    }

    @Bean
    ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager());
        Map<String, String> urlMap = new HashMap<>();

        // swagger
        urlMap.put("/swagger**/**", "anon");
        urlMap.put("/webjars/**", "anon");
        urlMap.put("/v2/api-docs", "anon");
        urlMap.put("/doc.html", "anon");

        urlMap.put("/user/**", "anon");

        urlMap.put("/**", "authc");
        bean.setFilterChainDefinitionMap(urlMap);

        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("authc", new CustomShiroFilter());
        bean.setFilters(filterMap);

        return bean;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
        return authorizationAttributeSourceAdvisor;
    }
}
